<?php

namespace openapi\controllers;

use common\utils\ApiHelper;
use peng\helpers\Config;

/**
 * 控制器-异步请求
 *
 * @author peng.huang
 */
class AjaxRequestController extends \openapi\controllers\base\OpenAPIController {

    /**
     * 模型对象
     * 
     * @var object 
     */
    public $model;

    /**
     * 执行
     * 
     * @param string $methodType [方法类型]
     */
    public function actionRun($methodType = NULL) {
        $result = array();
        if ($this->_checkValid($methodType) && $this->_process($result)) {
            $this->_reponseResult->result = 1;
            $this->_reponseResult->data = $result;
        }

        $this->response->setHeaders(array('Content-type' => 'text/json'));
        echo json_encode($this->_reponseResult);
    }

    /**
     * 验证数据是否正确
     * 
     * @param string $methodType [方法类型]
     * @return boolean
     */
    protected function _checkValid($methodType) {
        $request = json_decode(file_get_contents('php://input'));
        if (empty($request) || !is_object($request)) {
            return $this->_addError('输入值不符合json格式。');
        }

        $this->model = $this->_getModel($methodType, $request);
        if (FALSE === $this->model) {
            return $this->_addError('该对象无效。');
        }

        /*
        // 验证时间戳
        $expired = Config::get('config', 'timestamp_expire', 120);
        if (!isset($this->model->timestamp) || $this->model->timestamp > time() || $this->model->timestamp + $expired < time()) {
            return $this->_addError('时间戳错误或已过期。');
        }

        // 验证加密字符串
        if ($this->model->key !== ApiHelper::getEncryptdStr($this->model->timestamp)) {
            return $this->_addError('加密字符串错误。');
        }
*/
        return TRUE;
    }

    /**
     * 处理业务逻辑
     * 
     * @param array $result [&输出结果]
     * @return boolean
     */
    protected function _process(&$result) {
        if (!$this->model->commit($result)) {
            return $this->_addError($this->model->getErrors());
        }

        return TRUE;
    }

    /**
     * 返回模型对象
     * 
     * @param string $methodType [方法类型]
     * @param object $request [请求对象]
     * @return mixed
     */
    protected function _getModel($methodType, $request) {
        $relats = include dirname(__DIR__) . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'Relation.php';
        if (isset($relats[$methodType])) {
            $model = new $relats[$methodType]();
            foreach ($request as $key => $val) {
                property_exists($model, $key) AND $model->$key = $val; // 只赋值对象已存在的属性
            }

            return $model;
        }

        return FALSE;
    }

}
